<template>
	<view>
		<view class="page">
			<view class="cardView">
				
				<view class="commitment-container">
					<view class="container">
						<text>本人作为食品生产许可现场核查人员,在</text>
						
						<view class="edit-item" @click="openDatePicker('checkStartTime')">
							{{ selectedRow.checkStartTime || '点击选择日期' }}
						</view>
						<text>至</text>
						<view class="edit-item" @click="openDatePicker('checkEndTime')">
							{{ selectedRow.checkEndTime  || '点击选择日期' }}
						</view>
						<text>对</text>
						<view class="edit-item" @click="handleInput('applicationContent')">
							{{ selectedRow.operatorName  || '编辑' }}
						</view>
						<text>实施现场核查工作中，将依法依规履行职责，做到依法、公平、公正、廉洁、自律。本人承诺如下：</text>
								
					</view>
						
				</view>
			

					

				<view v-for="(item, index) in remarkList" :key="index" class="remark-item">
					<text class="remark-text">{{ item.remark }}</text>
				</view>
			</view>
			<view class="cardView">
				<!-- 经办人签名 -->
				<SignatureBlock label="承诺人" :sign-image.sync="selectedRow.checkPersonnelSignOne"
					:date.sync="selectedRow.checkSignDateOne" @open-date-picker="openDatePicker('checkSignDate')" />
			</view>

			<view class="cardView">
				<uni-title type="h4" title="本企业已知悉现场核查记录,并自觉维护现场核查工作的严肃性、廉洁性和公正性" align="center"></uni-title>

				<!-- 企业法人或负责人签名 -->
				<SignatureBlock label="企业法人或负责人签名" :sign-image.sync="selectedRow.centerPersonSign"
					:date.sync="selectedRow.centerPersonDate" @open-date-picker="openDatePicker('foodPersonDate')" />
			</view>


		</view>

		<view v-if="editStatus!='FALSE'" class="button-container">
			<view class="button-save">
				<button style="flex: 1;" type="primary" @click="submitForm('1')">保存并提交承诺书</button>
			</view>
			<view class="button-save">
				<button style="flex: 1;" type="primary" @click="submitForm('0')">暂存</button>
			</view>
		</view>
		
		<!-- 添加日期选择弹窗 -->
		<uni-popup ref="datePopup" type="dialog">
			<uni-popup-dialog mode="base" title="选择日期" @confirm="handleDialogConfirm" @close="handleDialogClose">
				<uni-datetime-picker type="date" @change="handleDateChange" />
			</uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	import SignatureBlock from '@/components/signature/signature.vue'
	import {
		foodProductionAdd,
		getMedicalDict,foodProductionInfo,foodProductionUpdate
	} from '@/api/order';
	export default {
		components: {
			SignatureBlock
		},
		computed: {
		    dateRangeDisplay() {
		      if (this.selectedRow.checkStartTime && this.selectedRow.checkEndTime) {
		        return `${this.selectedRow.checkStartTime} 至 ${this.selectedRow.checkEndTime}`
		      }
		      return ''
		    }
		  },
		data() {
			return {
				selectedDateRange: [], // 存储日期范围数组
				editStatus: 'ADD',
				remarkList: [], //文本
				selectedRow: {
					checkStartTime: '',
					checkEndTime: '',
					operatorName: '',
					bidType: '',
					checkPersonnelSignOne: '',
					checkSignDateOne: '',
					centerPersonSign: '',
					centerPersonDate: '',
					signDate: '', // 存储签名日期
					signatureImage: '', // 存储签名图片
					workOrderId: '',
					createBy: "管理员",
					auditStatus: ""
				},
				editDateType:'',
				tempDate:''
			}
		},


		onLoad(options) {
			if (options.editStatus != null) {
				const editStatus = decodeURIComponent(options.editStatus);
				const workOrderId = decodeURIComponent(options.workOrderId);
				this.selectedRow.workOrderId = workOrderId;
				this.editStatus = editStatus;
				this.getfoodProductionInfo(workOrderId);
			} else {
				if (options.orderData) {
					const orderData = JSON.parse(decodeURIComponent(options.orderData));
					const orderid = decodeURIComponent(options.workOrderId);
					this.selectedRow.bidType = orderData.bidType;
					this.selectedRow.workOrderId = orderid;
					this.selectedRow.operatorName=orderData.operatorName;
					this.selectedRow.orderCategory = orderData.orderCategory;
				}
			}

			this.getMedicalDict('integrity_book');

		},
		methods: {
			// 获取工单详情
			async getfoodProductionInfo(orderId) {
				const id = {
					workOrderId: orderId
				}
				const res = await foodProductionInfo(id);
				if (res.code === 0) {
					this.selectedRow = res.data;
				}
			},
			handleDialogClose(){
				this.$refs.datePopup.close();
			},
			handleInput(type) {
			
				uni.showModal({
					title: `请输入信息`,
					content: this.selectedRow.operatorName,
					editable: true,
					placeholderText: '请输入内容',
					success: res => {
						if (res.confirm) {
							this.$set(this.selectedRow, type, res.content)
							//this.$set(this.selectedRow, type, res.content); // 确保响应式更新
							this.selectedRow.operatorName = res.content
						}
					}
				})
			},
			
			// 打开日期选择器
			openDatePicker(type) {
				this.editDateType = type;
				console.log(this.editDateType )
				this.$refs.datePopup.open();
			},
			// 日期变化暂存
			handleDateChange(e) {
				this.tempDate = e ? new Date(e) : null;
			}, // 弹窗确认
			// 修改handleDialogConfirm方法
			handleDialogConfirm() {
				if (this.tempDate) {
					const year = this.tempDate.getFullYear();
					const month = (this.tempDate.getMonth() + 1).toString().padStart(2, '0');
					const day = this.tempDate.getDate().toString().padStart(2, '0');
					const formattedDate = `${year}-${month}-${day}`;
					if (this.editDateType === 'checkStartTime') {
						this.selectedRow.checkStartTime = formattedDate;
					} else if (this.editDateType === 'checkEndTime') {
						this.selectedRow.checkEndTime = formattedDate;
					} else if (this.editDateType === 'deliveryReceiptTime') {
						this.selectedRow.deliveryReceiptTime = formattedDate;
					}
			
				}
			
				this.$refs.datePopup.close();
			},
				// 新增初始化方法
				initDateRange() {
					if (this.selectedRow.checkStartTime && this.selectedRow.checkEndTime) {
						// 将字符串日期转换为时间戳
						const start = new Date(this.selectedRow.checkStartTime).getTime()
						const end = new Date(this.selectedRow.checkEndTime).getTime()
						this.selectedDateRange = [start, end]
					}
				},
				    handleDateRangeChange(e) {
				      console.log('日期选择结果:', e)
				      let values = Array.isArray(e) ? e : e?.detail?.value || []
				      
				      // 更新日期范围数据（存储时间戳）
				      this.selectedDateRange = values
					  console.log("this.selectedDateRange"+this.selectedDateRange)
				      // 转换为YYYY-MM-DD格式
				      if (values.length === 2) {
				        this.selectedRow.checkStartTime = values[0]
				        this.selectedRow.checkEndTime = values[1]
				      }
				      console.log('当前时间范围:', this.selectedRow)
				    },
				
				    formatDate(timestamp) {
				      if (!timestamp) return ''
				      const date = new Date(Number(timestamp))
				      return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
				    },
		
		
			// 日期确认回调
			handleDateConfirm(date) {
				this.$set(this.selectedRow, this.currentDateType, date);
				this.showDatePopup = false;
			},
			//获取字典值
			async getMedicalDict(type) {
				try {
					const res = await getMedicalDict(type)

					// 增加响应状态判断
					if (res.code === 0) {
						switch (type) {
							case 'integrity_book':
								this.remarkList = res.data;
								console.log(res.data)
								break;
							case '2017':

							case 'bid_type':
								this.valueOptions = res.data.map(item => ({
									text: item.label,
									value: String(item.value) // 确保字典值转为字符串
								}));
								break;
							case 'mode_of_operation':
								this.modeOptions = res.data.map(item => ({
									text: item.label,
									value: String(item.value) // 确保字典值转为字符串
								}));


								break;

							default:
								return;
						}
					} else {
						throw new Error(res?.data?.msg || '接口返回异常')
					}

				} catch (error) {
					uni.showToast({
						title: error.message || '获取分类失败',
						icon: 'none',
						duration: 2000
					})
				}
			},
		
			handleDateConfirm(date) {
				this.$set(this.selectedRow, this.currentDateType, date)
			}, // 提交方法
			
			async submitForm(status) {
				try {
					// 状态校验前置
					if (this.editStatus === 'FALSE') {
						return uni.showToast({
							title: '当前处于查看状态',
							icon: 'none'
						});
					}
					// 统一处理提交逻辑
					const isEditMode = this.editStatus === 'EDIT';
					const apiMethod = isEditMode ? foodProductionUpdate : foodProductionAdd;
					// 构造请求参数（避免污染原始数据）
					const payload = {
						...this.selectedRow,
						auditStatus: status,
					};
			
					// 显示加载状态
					uni.showLoading({
						title: '提交中...',
						mask: true
					});
			
					console.log(payload)
					// 执行API调用
					const res = await apiMethod(payload);
			
					if (res.code !== 0) {
						throw new Error(res.msg || '服务器处理异常');
					}
			
					// 统一处理成功逻辑
					uni.showToast({
						title: '提交成功',
						icon: 'success'
					});
			
				// 关闭当前页面，跳转到工单页
				this.$closeAndRedirect({
				  url: '/pages/work/history/index'
				});
				} catch (error) {
					// 统一错误处理
					console.error('提交失败:', error);
					uni.showToast({
						title: error.msg || '请求失败，请检查网络',
						icon: 'none',
						duration: 3000
					});
				} finally {
					uni.hideLoading();
				}
			},

		}
	}
</script>


<style>
	.page {
		background-color: #e9f1fe;
		padding: 20px;
	}

	.cardView {
		margin-bottom: 10px;
		padding: 15px;
		background: #ffffff;
		border-radius: 8px;
		box-shadow: 0 2px 12px rgba(0, 0, 0, 0.12);
	}

	.remark-text {
		font-size: 15px;
		line-height: 1.6;
		margin-top: 18px;
		/* 关键行：设置行高 */
		display: block;
		/* 确保独占一行，行高生效 */
		margin-bottom: 18px;
		text-indent: 2em
			/* 可选：段落间距 */
	}

	
	.commitment-container {
		text-indent: 2em;
		font-size: 16px;
	}
	

	.inline-block {
		display: inline-block;
	}

	.date-box {
		min-width: 4em;
		border-bottom: 1px solid #666;
		padding: 0 8rpx;
	}

	.date-box2 {
		min-width: 4em;
		border-bottom: 1px solid #666;
		padding: 0 8rpx;
		text-align: center;
		font-size: 17px;
		/* 修改方案 */
		padding-top: 5px;
		padding-bottom: 0px;
		/* 减少底部内边距 */
		line-height: 1.1;
		/* 调整行高 */
	}

	/* 如果需要更精确控制输入框位置 */
	.date-box2 input {
		padding-bottom: 1;
		/* 移除输入框自带的内边距 */
		margin-bottom: -2px;
		/* 微调位置 */
	}

	.production-input {
		border-bottom: 1px solid #666;
		padding: 0 8rpx;
		width: 200rpx;
	}

	.button-container {
		display: flex;
		background-color: #ffffff;
		width: 100%;
		padding: 10px;
		flex-direction: column;
		/* 垂直排列 */

		.button-save {
			margin-bottom: 10px;
		}

		.button-child {
			display: flex;
			flex-direction: row;
			/* 垂直排列 */

		}
	}
	
	.edit-item {
		display: inline-block;
		min-width: 80rpx;
		border-bottom: 1px solid #000000;
		color: #2e31ee;
		padding: 0 10rpx;
		margin: 0 8rpx;
	}
	
	
</style>